<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="自定义名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入自定义名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="关联设备id组" prop="deviceIds">
        <el-input
          v-model="queryParams.deviceIds"
          placeholder="请输入关联设备id组"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:alarms:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:alarms:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:alarms:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:alarms:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="alarmsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="自增主键" align="center"   type="index"  :index="indexMethod">
      </el-table-column>
      <el-table-column label="自定义名称" align="center" prop="name" />
      <el-table-column label="关联设备id组" align="center" prop="deviceIds" />
      <!-- <el-table-column label="状态" align="center" prop="status" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:alarms:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:alarms:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改自定义报警列配置对话框 -->
    <el-dialog :title="title" :visible.sync="open"    width="800px" :append-to-body="true">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="自定义名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入自定义名称" />
        </el-form-item>
        <el-form-item  label="关联设备id组"  prop="deviceIds">
          <!-- <el-button type="primary" @click="selectDevices" >选择设备</el-button> -->
          <el-popover
            title="选择设备"
            v-model="showPop"

            width="800"
            height="600"
            trigger="click">
            <!-- <el-form>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form> -->
            <el-table  max-height="250" :data="gridData" ref="propTable"  @selection-change="handleSelectionChangePop" :row-key="getRowKeys" >

              <el-table-column
                type="selection"
                width="55" :reserve-selection="true">
              </el-table-column>
              <el-table-column label="序号" align="center"  width="60"   type="index"  :index="indexMethod1">
              </el-table-column>
              <el-table-column label="设备归属" align="center" prop="belongName" />
              <el-table-column width="150" property="deviceId" label="设备ID"></el-table-column>
              <el-table-column label="设备地址代号_序号" align="center" prop="systemId" >
                <template slot-scope="scope">
                  <!-- <router-link :to="{path:'/system/device-data/index',query:{systemId:scope.row.systemId,modality:scope.row.modality}}" class="link-type"> -->
                  <el-button type="text" @click="queryDetail(scope.row)">{{scope.row.systemId }}</el-button>
                  <!-- </router-link> -->
                </template>
              </el-table-column>
              <el-table-column label="设备类型" align="center" prop="modality">
                <template slot-scope="scope">
                  <dict-tag
                    :options="dict.type.modality_list"
                    :value="scope.row.modality"
                  />
                </template>
              </el-table-column>
              <el-table-column label="显示的名称" align="center" prop="deviceName" />

            </el-table>

            <pagination
              v-show="pop.Total > 0"
              :total="pop.Total"
              :page.sync="pop.queryParams.pageNum"
              :limit.sync="pop.queryParams.pageSize"
              @pagination="getData"
            />



            <div class="mar-top-10" style="overflow: hidden;margin-top:30px;">
              <el-button size="mini" style="float:right" class="FloatRight"   icon='el-icon-circle-close' @click="showPop=false" >取消</el-button>
              <el-button size="mini"  type="success" class="card-title-button"  @click="handleSelectData" style="margin-right:10px;float:right;" icon='el-icon-circle-check'>确定</el-button>
            </div>
            <el-button slot="reference" >选择设备</el-button>
          </el-popover>
          <el-table :data="dataSel" height="250" border>
            <el-table-column label="序号" align="center" prop="id" width="60">
              <template slot-scope="scope">
                <span>{{ scope.$index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="belongName" label="设备归属" ></el-table-column>
            <el-table-column width="150" prop="deviceId" label="设备ID"></el-table-column>
            <el-table-column label="设备地址代号_序号" align="center" prop="systemId" >
              <template slot-scope="scope">
                <el-button type="text" @click="queryDetail(scope.row)">{{scope.row.systemId }}</el-button>
              </template>
            </el-table-column>
            <el-table-column label="设备类型" align="center" prop="modality">
              <template slot-scope="scope">
                <dict-tag
                  :options="dict.type.modality_list"
                  :value="scope.row.modality"
                />
              </template>
            </el-table-column>
            <el-table-column label="显示的名称" align="center" prop="deviceName" />

          </el-table>

        </el-form-item>
        <!-- <el-form-item label="关联设备id组" prop="deviceIds">
          <el-input v-model="form.deviceIds" placeholder="请输入关联设备id组" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAlarms, getAlarms, delAlarms, addAlarms, updateAlarms } from "@/api/system/alarms";
import {listDevice,listDevsNoPage} from "@/api/system/device";
export default {
  dicts: [
    "modality_list"],
  name: "Alarms",
  watch:{
    showPop(n,o){
      if(n==true){
        this.getData() ;
      }

    }
  },

  data() {
    return {
      pop:{
        Total:0,
        queryParams:{
          pageNum:1,
          pageSize:10
        }
      },
      multipleSelection: [],
      showPop:false,
      gridData: [],
      
      show:false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      dataSel:[],
      // 自定义报警列配置表格数据
      alarmsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        deviceIds: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    indexMethod1(index) {

return index + 1 + (this.pop.queryParams.pageNum- 1) * this.pop.queryParams.pageSize

  },
    indexMethod(index) {

return index + 1 + (this.queryParams.pageNum- 1) * this.queryParams.pageSize

  },
    queryDetail(row){
      this.open=false;
      this.$router.push({ path: '/system/device-data/index', params: {systemId:row.systemId,modality:row.modality}} )
    },
    getRowKeys(row) {
      return row.deviceId
    },
    /** 查询设备列表 */
    getData() {
      this.loading = true;
      listDevice(this.pop.queryParams).then((response) => {
        this.gridData=[];
        this.gridData = response.rows;
        this.pop.Total = response.total;
        this.loading = false;
        if(this.gridData && this.gridData.length>0){
          this.$nextTick(()=>{
            this.toggleRowSelection( )

            // this.rowSelectFlag = false
          });

        }
      });
    },
    handleSelectionChangePop(val){
      this.multipleSelection=val ;

    },
    async toggleRowSelection () {
      //切换的效果需要先清空数据
      // await this.$refs.multipleUserTable.clearSelection()
      this.gridData.forEach(item=>{
        let c = this.dataSel.find(data => {
          console.log(item.deviceId+"==="+data.deviceId )
          return item.deviceId == data.deviceId // 注意这里寻找的字段要唯一，示例仅参考
        })
        if(c){
          console.log("11111")
          this.$refs.propTable.toggleRowSelection(item,true);
        }else{

        }

      })

    },

    tableRowClick(row,type){  //单选列表行点击事件
      console.log(type,row);
    },
 
    cancelPop(){
      this.visible = false
    },
    handlePopoverShow(){  //弹出框显示触发
      this.$emit('handlePopoverShow',true)
    },
    handleSizeChange(val) { //分页条数
      this.$emit('handleSizeChange',val)
    },

    handleSelectData(){	//确认触发事件
      this.dataSel=[];
      this.dataSel=this.multipleSelection;
      console.log(this.dataSel)
      this.showPop = false
    },
    selectDevices(){
      this.show=true;
    },
    /** 查询自定义报警列配置列表 */
    getList() {
      this.loading = true;
      listAlarms(this.queryParams).then(response => {
        this.alarmsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        deviceIds: null,
        status: "0"
      };
      this.dataSel=[];
      if(this.$refs.propTable){
        this.$refs.propTable.clearSelection()
      }

      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加自定义报警列配置";
      this.form.name="自定义报警显示列表"+(this.total+1);
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getAlarms(id).then(response => {
        this.form = response.data;
        listDevsNoPage({"deviceIds":this.form.deviceIds}).then(res=>{
          // var alarmsList = res.data;
          // this.dataSel== res.data;
          this.dataSel=res.data.map(item=>{
            return {deviceId:item.deviceId,systemId:item.systemId,modality:item.modality,deviceName:item.deviceName}
          });
          // if(alarmsList && alarmsList.length>0){
          //   this.dataSel= alarmsList.map(alarm=>{
          //       return{

          //       }
          //   })
          // }
        })
        // var ids =this.form.deviceIds.split(",");
        // //查询设备关联字段
        // this.dataSel=ids.map(id=>{
        //   return {deviceId:id}
        // });

        this.open = true;
        this.title = "修改自定义报警列配置";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if(this.dataSel && this.dataSel.length>0){
            this.form.deviceIds = this.dataSel.map(item=>{
              return item.deviceId;
            }).toString();
          }else{
            this.$message.error("请选择关联设备id组");
            return;
          }

          if (this.form.id != null) {
            updateAlarms(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.reset();
              this.getList();
            });
          } else {
            addAlarms(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.reset();
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除自定义报警列配置编号为"' + ids + '"的数据项？').then(function() {
        return delAlarms(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/alarms/export', {
        ...this.queryParams
      }, `alarms_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
